<script setup>
import { register_article_list, submitReject, editSubmitReject, register_batch_list, register_withdrawApply } from '@/api/reject/register.js';
import { ElMessageBox, ElMessage } from 'element-plus'

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});
const articleBatch = ref([])
const loading = ref(false);
const totalV = ref(0);
const articleList = ref([]);
const queryFormRef = ref();
const ids = ref([]);
const items = ref([]);
const dialog = ref({
  title: "",
  visible: false,
});
const unShowColumn = ref(false)
const multipleTableRef = ref()//清多选
/** 查询 */
function handleQuery() {
  loading.value = true;
  register_article_list(queryParams.value)
      .then(({ rows, total }) => {
        articleList.value = rows;
        totalV.value = total;
      })
      .finally(() => {
        loading.value = false;
      });
}

// 获取批次列表
function getBatchList() {
  register_batch_list().then((res) => {
    articleBatch.value = res.data.map(item => ({ label: item.name, value: item.id }));
  })
}
/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}


/** 行checkbox 选中事件 */
function handleSelectionChange(selection) {
  // ids.value = selection.map((item) => ({ batchId: item.batchId, productsId: item.productsId, productsName: item.productsName }));
  ids.value = selection;
}

// const toggleSelection = (rows) => {
//   if (rows) {
//     rows.forEach((row) => {
//       // TODO: improvement typing when refactor table
//       // eslint-disable-next-line @typescript-eslint/ban-ts-comment
//       // @ts-expect-error
//       multipleTableRef.value!.toggleRowSelection(row, undefined)
//     })
//   } else {
//     multipleTableRef.value!.clearSelection()
//   }
// }

/** 打开表单弹窗 */
function openDialog(row) {

  dialog.value.visible = true;



  // if (row.applyWasteId === null) {
  dialog.value.title = "申请报废处理";

  if (ids.value.length === 0) {
    let itemTemp = {
      // id: row.id,
      batchId: row.batchId,
      productsId: row.productsId,
      objectName: row.productsName,
      flag: 1,
      applyWasteId: row.applyWasteId,
      batchName: row.batchName,
      productsNum: row.productsNum,
      productsUnqualified: row.productsUnqualified
    };
    items.value.push(itemTemp)
  } else {
    items.value = ids.value.map(item => ({
      // id:item.id,
      batchId: item.batchId,
      productsId: item.productsId,
      objectName: item.productsName,
      flag: 1,
      applyWasteId: item.applyWasteId,
      batchName: item.batchName,
      productsNum: item.productsNum,
      productsUnqualified: item.productsUnqualified
    }));
  }
  // }

  // if (row.applyWasteId !== null) {
  //     dialog.value.title = "修改报废申请";

  //     let itemTemp = {
  //         id: row.id,
  //         batchId: row.batchId,
  //         productsId: row.productsId,
  //         objectName: row.productsName,
  //         flag: 1,
  //         objectAmount: row.productsUnqualified,
  //         applyWasteId: row.applyWasteId
  //     };
  //     items.value.push(itemTemp)



  // }
}

/** 保存提交 */
function handleSubmit() {

  loading.value = true;

  // ElMessageBox.confirm("确认提交报废么？", "警告", {
  //     confirmButtonText: "确定",
  //     cancelButtonText: "取消",
  //     type: "warning",
  // }).then(
  //     function () {
  //         return submitReject(items.value[0])
  //     }
  // )

  // if(items.value[0].applyWasteId===null){

  items.value.map((item) => {

    submitReject(item).then(() => {
      ElMessage.success("提交成功");
      // dialog.value.visible = false;
      closeDialog();
      resetQuery();
    })
        .finally(() => (loading.value = false));
  })

  // }

  // if(items.value[0].applyWasteId!==null){
  //     editSubmitReject(items.value[0]).then(() => {
  //         ElMessage.success("提交成功");
  //         // dialog.value.visible = false;
  //         closeDialog();
  //         resetQuery();
  //     })
  //     .finally(() => (loading.value = false));}

}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.value.visible = false;
  multipleTableRef.value.clearSelection()
  // resetForm();
  ids.value = []
  items.value = []
}

/** 打开表单弹窗 */
function checkSubmit(row) {

  ElMessageBox.confirm('确定撤回吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(
          async () => {
            // 请求接口 删除数据
            let r = await register_withdrawApply(row.applyWasteId)
            if (r.code === 200) {
              ElMessage({ type: 'success', message: '撤回成功' })
            } else {
              ElMessage({ type: 'info', message: r.data })
            }
          }
      ).catch(() => {
    ElMessage({
      type: 'info', message: '撤回失败'
    })
  }).finally(() => {
    handleQuery()
  })
}

const articleStatus = ref([{ value: 1, label: '待审核' }, { value: 0, label: '已通过' }, { value: 2, label: '已驳回' }])

// 计算属性，用于获取 status 对应的标签类型（可选，取决于你是否需要为标签设置不同的类型）
const getStatusType = computed(() => {
  const typeMap = {
    1: 'info', // 例如：待审核为信息类型
    0: 'success', // 已通过为成功类型
    2: 'warning', // 已驳回为警告类型
  };
  return (status) => typeMap[status] || 'default'; // 默认类型
});

// 方法，用于根据 status 获取对应的 label
function getStatusLabel(status) {
  return articleStatus.value.find((item) => item.value === status)?.label || '未操作';
}

onMounted(() => {
  handleQuery();
  getBatchList();
});
</script>

<template>
      <el-card class="page-container">

  <!-- <div class="app-container">
    <div class="search-container">
      <el-card shadow="hover" class="elCard"> -->
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">

          <el-form-item prop="productsName" label="用品名称">
            <el-input v-model="queryParams.productsName" placeholder="用品名称" clearable
                      @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="批次" prop="batchId">
            <el-select v-model="queryParams.batchId">
              <el-option v-for="(item, index) in articleBatch" :index="item.value" :key="index"
                         :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery"><el-icon>
              <Search />
            </el-icon>搜索</el-button>
            <el-button @click="resetQuery"><el-icon>
              <Refresh />
            </el-icon>重置</el-button>
          </el-form-item>
        </el-form>
      <!-- </el-card>
    </div> -->

    <!-- <el-card shadow="never" class="table-container"> -->
      <!-- <template #header> -->
        <div class="mb8">
        <el-button type="primary" plain icon="Plus" :disabled="ids.length === 0" @click="openDialog()">批量报废处理</el-button>
        <!-- </template> -->
      </div>
      <el-table v-loading="loading" :data="articleList" highlight-current-row border stripe height="520"
                style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" align="center" width="55">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="记录id" prop="id" min-width="100" v-if="unShowColumn" />
        <el-table-column label="用品id" prop="productsId" min-width="100" v-if="unShowColumn" />
        <el-table-column label="批次id" prop="batchId" min-width="100" v-if="unShowColumn" />
        <el-table-column label="用品名称" prop="productsName"   align="center"/>
        <el-table-column label="所属批次" prop="batchName"  align="center"/>
        <el-table-column label="用品库存数量" prop="productsNum"   align="center"/>
        <el-table-column label="用品待报废总数" prop="productsUnqualified"   align="center"/>
        <!-- <el-table-column label="申请报废数量" prop="productsApply"  align="center"/> -->
        <!-- <el-table-column label="报废处理状态" align="center" prop="flag">
            <template #default="scope">

            <el-tag :type="getStatusType(scope.row.flag)">
                {{ getStatusLabel(scope.row.flag) }}
            </el-tag>
            </template>
        </el-table-column> -->
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template #default="scope">

            <!-- v-if="scope.row.applyWasteId === null"  -->
            <el-button type="primary" size="small" link @click="openDialog(scope.row)"><el-icon>
              <DeleteFilled />
            </el-icon>申请报废处理
            </el-button>
            <!-- <el-button v-if="scope.row.applyWasteId !== null" type="primary" size="small" link
                @click="openDialog(scope.row)"><el-icon>
                    <Edit />
                </el-icon>修改报废申请
            </el-button>
            <el-button v-if="scope.row.applyWasteId !== null" type="primary" size="small" link
                @click="checkSubmit(scope.row)"><el-icon>
                    <RefreshLeft />
                </el-icon>撤回
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                     :page-sizes="[10, 20, 30, 40]" :background="true" layout="total, sizes, prev, pager, next, jumper"
                     :total="totalV" @size-change="handleQuery" @current-change="handleQuery" style="margin-top: 20px; justify-content: flex-end" />
    <!-- </el-card> -->

    <!-- 表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="700px" @close="closeDialog" draggable>
      <div>
        <div v-for="(item, index) in items" :key="item.id" class="item-container">
          <!-- 展示name -->
          <!-- <span class="item-name">{{item.batchName}}</span> -->
          <span class="item-nameC">{{ item.objectName }}({{ item.batchName }})的报废数量:</span>

          <!-- <span class="item-name">
              <span>{{item.batchName}}</span><span>
                  {{item.objectName }}的报废数量:
              </span>
              </span> -->


          <!-- 输入框，用于输入数量 -->
          <!-- <input type="number" class="item-input" v-model="item.objectAmount" >   -->
          <el-input-number v-model="item.objectAmount" :min="0"
                           :max="item.productsNum - item.productsUnqualified" :style="{ width: '200px' }"
                           placeholder="输入报废数量" />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
  <!-- </div> -->
</template>

<style scoped>

.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .mb8 {
    margin-bottom: 8px;
  }
}

.elCard {
  margin-bottom: 10px;
}

.el-card {
  --el-card-padding: 12px;
}

.el-pagination {
  margin-top: 10px;
  margin-left: 10px;
}

.item-container {
  /* 根据需要设置容器的宽度，或者让它自适应 */
  /* width: 100%; */
  display: flex;
  /* 使用flex布局可以更容易地对齐子元素 */
  align-items: center;
  /* 垂直对齐子元素 */
}

.item-name {
  display: inline-block;
  /* 确保span元素在同一行内 */
  width: 150px;
  /* 设置span的宽度 */
  text-align: end;
  margin-right: 5px;
  font-size: 16px;
  line-height: 40px;

  /* 其他样式，如字体大小、颜色等 */
}

.item-nameC {
  display: inline-block;
  /* 确保span元素在同一行内 */
  width: 300px;
  /* 设置span的宽度 */
  text-align: end;
  margin-right: 10px;
  font-size: 16px;
  line-height: 40px;

  max-width: 300px;
  /* 或者你需要的任何值 */

  /* 确保内容在超出宽度时换行 */
  overflow-wrap: break-word;
  word-wrap: break-word;


  /* 其他样式，如字体大小、颜色等 */
}

.item-input {
  display: inline-block;
  /* 确保input元素在同一行内 */
  width: 300px;
  /* 设置input的宽度 */
  /* 其他样式，如边框、内边距等 */
}
</style>